<?php
/**
 * Description of CommentFacade
 *
 * @author Alexey
 */
class CommentFacade {

    public static function saveModel(Comment $comment)
    {
        $comment->author_id = Yii::app()->controller->getUserIdFromSession();
        if (!$comment->save())
        {
            echo CVarDumper::dumpAsString($comment->getErrors());
            Yii::log("CommentFacade: ".CVarDumper::dumpAsString($comment->getErrors()), CLogger::LEVEL_ERROR, "application.models.facade.CommentFacade");
            throw new CHttpException(500, "Could not save comment");
        }
        return $comment;
    }

    public static function loadModel($id)
    {
        $model=Comment::model()->findByPk((int)$id);
        if($model===null)
                throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }

    private static function getCommentDBCriteriaByCommentFlowId($commentFlowId)
    {
        $criteria = new CDbCriteria();
        $criteria->condition = 'comment_flow_id = :commentFlowId';
        $criteria->params[':commentFlowId'] = $commentFlowId;
        $criteria->order = "publish_date ASC";
        return $criteria;
    }

    public static function getLatesComment($commentFlowId, $count = 0)
    {
        $criteria = CommentFacade::getCommentDBCriteriaByCommentFlowId($commentFlowId);
        if ($count)
        {
            $criteria->limit = $count;
        }
        return Comment::model()->findAll($criteria);
    }

    public static function getLatesCommentCount($commentFlowId)
    {
        $criteria = CommentFacade::getCommentDBCriteriaByCommentFlowId($commentFlowId);
        return Comment::model()->count($criteria);
    }

    public static function isAuthor(Comment $comment)
    {
        $userId = Yii::app()->controller->getUserIdFromSession();
        if ($userId == $comment->author_id)
        {
            return true;
        }
        return false;
    }

    public static function deleteCommentFlowModel($commentFlowId)
    {
        $model = CommentFacade::loadCommentFlowModel( $commentFlowId);
        $model->delete();
    }

    public static function loadCommentFlowModel($commentFlowId)
    {
        $model=CommentFlow::model()->findByPk((int)$commentFlowId);
        if($model===null)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }

}
?>
